var num = 7;
var arrGame = [];
var parentOff;
var animating = false;
var __arr = [];
var mnclick = false;
$(function(){
   arrGame = $("#games .game").find("div");
   parentOff = $("#games .game").offset();
   for(var i  = 0 ; i < arrGame.length; i++){
        var l = 30 + i * 140;
        $(arrGame[i]).offset({left : parentOff.left + l});
   }
   if(arrGame.length <= num) $("#games .nav").hide();
   $("#games .prev").click(function(){
        changeSlide(-1);
   });
   $("#games .next").click(function(){
        changeSlide(1);
   });
});

function changeSlide(a){
    if(animating) {
        if(mnclick)
            __arr.push(a);
        return;
        
        
    };
    if(arrGame.length <= num) return;
    
    animating = true;
    var d = (a > 0) ? 0 : arrGame.length - 1;
    var e = (a > 0) ? arrGame.length - 1 : 0;
    
    var c = (a > 0) ? arrGame[e] : arrGame[e];
    var o = (a > 0) ? $(arrGame[d]).offset().left -  140 : $(arrGame[d]).offset().left;
    if(a > 0)
        $(c).offset({left : o});
    
    for(var i  = 0 ; i < arrGame.length; i++){
       var l = $(arrGame[i]).offset().left + a * 140 - parentOff.left;
       $(arrGame[i]).animate({
            left : l
       },500,function() {
            if(animating) {
                animating = false;
                if(a < 0){
                     $(c).offset({left : o});
                    arrGame = moveArray(e, d, arrGame);
                }
                if(__arr.length > 0){
                    changeSlide(__arr[0]);
                    __arr.splice(0,1);
                }
               
            }
      });
    } 
    if(a > 0)
        arrGame = moveArray(e, d, arrGame);
}

function move(a,b){
    var l = $(a).offset().left + b * 140 - parentOff.left;
    $(a).animate({
        left : l
   },500,function() {
        if(animating) animating = false;
  });
}
function moveArray(old_index, new_index, arr) {
    while (old_index < 0) {
        old_index += arr.length;
    }
    while (new_index < 0) {
        new_index += arr.length;
    }
    if (new_index >= arr.length) {
        var k = new_index - arr.length;
        while ((k--) + 1) {
            arr.push(undefined);
        }
    }
    arr.splice(new_index, 0, arr.splice(old_index, 1)[0]);
    return arr; // for testing purposes
};